import("System")
import("System.IO.Ports")
import("Jodell.Tool","Jodell.Tool")

COMID = "COM5" --需要配置端口名称
SlaveStartID = 2 --需要设置的从站起始地址
SlaveEndID = 2 --需要设置的从站结束地址

--打开串口
client=Lua_ModbusRtuClient()
client.PortName=COMID
client:Connect()

--设备使能
for var=SlaveStartID,SlaveEndID,1 do
       ret = client:WriteUInt16(var,1002,1)
	if ret ~= 0 then
		Error( string.format("%d号设备设置使能失败",var))
		goto exit
	end
	Info( string.format("%d号设备设置使能成功",var))
end
--读使能状态
Delay(2000);
for var=SlaveStartID,SlaveEndID,1 do
       ret,runStatus = client:ReadUInt16(var,2000)
	if ret ~= 0 or runStatus ~= 4 then
		Error( string.format("%d号设备使能失败",var))
		goto exit
	end
	Info( string.format("%d号设备使能成功",var))
end

--循环推拉
while 1 do
	--终止测试
	if (IsCancel) then
		Error("手动退出")
		goto exit
	end
	--设置推动作
	for var=SlaveStartID,SlaveEndID,1 do
	       ret = client:WriteUInt16(var,1003,1)
		if ret ~= 0 then
			Error(string.format("%d号设备设置推失败",var))
			goto exit
		end
	end
	Delay(2000);
	--读动作状态
	for var=SlaveStartID,SlaveEndID,1 do
	       ret,runStatus = client:ReadUInt16(var,2001)
		if ret ~= 0 or runStatus ~= 10 then
			Error( string.format("%d号设备推失败",var))
			goto exit
		end
		Info( string.format("%d号设备推成功",var))
	end
	--设置拉动作
	for var=SlaveStartID,SlaveEndID,1 do
	       ret = client:WriteUInt16(var,1003,0)
		if ret ~= 0 then
			Error(string.format("%d号设备设置拉失败",var))
			goto exit
		end
	end
	Delay(2000);
	--读动作状态
	for var=SlaveStartID,SlaveEndID,1 do
	       ret,runStatus = client:ReadUInt16(var,2001)
		if ret ~= 0 or runStatus ~= 14 then
			Error( string.format("%d号设备拉失败",var))
			goto exit
		end
		Info( string.format("%d号设备拉成功",var))
	end	
end

::exit:: 
client:Disconnect()
Info("测试结束")
